
from django.shortcuts import get_object_or_404
from .models import *

from user.models import User
class Menus():
    def __init__(self,user_id=None):
        self.user_id =user_id
    def convert_menu_to_tree(self,menu_list):
        '''
        转换数据格式
        :param menu_list:
        :return:
        '''
        tree = []
        menu_dict = {menu.menuId: {'id': menu.menuId, 'label': menu.menuName, 'children': []} for menu in menu_list}

        for menu in menu_list:
            if menu.parentId:
                parent_menu = menu_dict.get(menu.parentId)

                if parent_menu:
                    parent_menu['children'].append(menu_dict[menu.menuId])
            else:
                tree.append(menu_dict[menu.menuId])

        return tree
    def _get_menu_treeselect(self):
        '''
        菜单下拉树结构
        :return:
        '''


        menus = SystemMen.objects.filter(status=1)

        return self.convert_menu_to_tree(menus)

    def select_menu_list_by_role_id(self):
        '''
        通过角色id 查询菜单id
        :return:
        '''

        try:
            user_role = SystemRoleMenu.objects.filter(role_id=self.user_id)
        except SystemRoleMenu.DoesNotExist:

            return {"errcode": 404, "mess": "用户id【%s】角色菜单不存在" % self.user_id}

        menu_roles = []
        for role in user_role:
            menu_roles.append(role.menu_id)

        return menu_roles

